import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import dynamicImport from 'vite-plugin-dynamic-import';
import { renderSync } from 'sass';
import fs from 'fs-extra';
import path from 'path';

function generateCSSFromScss(scssFilePath: string, outputDir: string) {
  const result = renderSync({ file: scssFilePath });
  const cssFileName = path.basename(scssFilePath, '.scss') + '.css';
  const outputPath = path.join(outputDir, cssFileName);
  fs.ensureDirSync(outputDir);
  fs.writeFileSync(outputPath, result.css);
}
// import { viteStaticCopy } from 'vite-plugin-static-copy';

// import sass from 'rollup-plugin-scss';

const inputFiles = {
  'home-index': 'src/styles/home-index.scss',
  'goods-index': 'src/styles/goods-index.scss',
  'search-index': 'src/styles/search-index.scss',
};

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    dynamicImport({
      // 插件选项
    }),
    {
      name: 'watch-scss-generate-css',
      apply: 'serve', // 只在开发环境下使用
      handleHotUpdate({ file }: any) {
        if (file.endsWith('.scss')) {
          // 定义输出目录
          const outputDir = path.resolve(__dirname, 'dist/styles');
          generateCSSFromScss(file, outputDir);
        }
      },
    },
  ],
  css: {
    preprocessorOptions: {
      scss: {
        // 配置 SCSS 相关选项
      },
    },
  },
  build: {
    rollupOptions: {
      input: inputFiles, // 指定多个入口文件
    },
  },
})
